package com.zqq.demo.service

import android.content.Intent
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.zqq.netty.NettyManager
import kotlinx.coroutines.launch


class MainService : LifecycleService() {

    private val dataTimeOut = 60 //收发超时
    private val readTimeOut = 60 // 读超时时间
    private val whiteTimeOut = 60 // 写超时时间

    var nettyManager:NettyManager? = null

    override fun onCreate() {
        super.onCreate()
        initSocket()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

    private fun initSocket() {
        var ip = ""
        val port = 0
        nettyManager = NettyManager(ip, port, dataTimeOut, readTimeOut, whiteTimeOut)
        lifecycleScope.launch {
            nettyManager?.connect() //连接
        }
        nettyManager?.setOnNettyListener(object :NettyManager.OnNettyListener{
            override fun onConnectSuccess() {

            }

            override fun onConnectFail(connectFailNum: Int) { //connectFailNum 重连失败次数
                if (connectFailNum >= 5) { //连接五次失败 修改ip重连
                    changeIp()
                }
            }

            override fun onReceiveData(bytes: ByteArray?) {

            }

            override fun onNeedReCreate() {
                initSocket()
            }
        })
    }

    /**
     * 修改ip 会自动重连
     */
    private fun changeIp() {
        nettyManager?.apply {
            ip = ""  //新的ip
            port = 1 //新的端口
        }
    }

    private fun closeSocket(){
        nettyManager?.let {
            it.close()
            nettyManager = null
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        closeSocket()
    }
}